<template>
  <div class="account-management">
    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="用户名">
          <el-input v-model="searchForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="searchForm.role" placeholder="请选择角色">
            <el-option label="全部" value="" />
            <el-option label="管理员" :value="1" />
            <el-option label="志愿者" :value="2" />
            <el-option label="组织" :value="3" />
            <el-option label="普通用户" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态">
            <el-option label="全部" value="" />
            <el-option label="正常" value="1" />
            <el-option label="禁用" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
          <el-button type="success" @click="handleAdd">新增用户</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 用户列表 -->
    <el-card class="table-card">
      <el-table :data="userList" stripe border v-loading="tableLoading">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="role" label="角色">
          <template #default="{ row }">
            <el-tag :type="getRoleType(row.role)">{{ getRoleName(row.role) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="phone" label="手机号" />
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column prop="status" label="状态">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="2"
              @change="(val) => handleStatusChange(row, val)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
            <el-button link type="primary" @click="handleResetPwd(row)">重置密码</el-button>
            <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 用户表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增用户' : '编辑用户'"
      width="500px"
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userRules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" :disabled="dialogType === 'edit'" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="userForm.role">
            <el-option label="管理员" :value="1" />
            <el-option label="志愿者" :value="2" />
            <el-option label="组织" :value="3" />
            <el-option label="普通用户" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="userForm.name" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="dialogType === 'add'">
          <el-input v-model="userForm.password" type="password" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getUserList, 
  addUser, 
  updateUser, 
  deleteUser, 
  changeUserStatus, 
  resetUserPassword 
} from '@/api/user'

// 搜索表单
const searchForm = reactive({
  username: '',
  role: '',
  status: ''
})

// 分页数据
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 加载状态
const tableLoading = ref(false)
const submitLoading = ref(false)

// 用户列表数据
const userList = ref([])

// 对话框控制
const dialogVisible = ref(false)
const dialogType = ref('add')
const userFormRef = ref(null)
const userForm = reactive({
  id: '',
  username: '',
  role: '',
  name: '',
  email: '',
  phone: '',
  password: '',
  status: '1'
})

// 表单校验规则
const userRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ]
}

// 获取角色标签类型
const getRoleType = (role) => {
  const types = {
    1: 'danger',    // 管理员
    3: 'warning',   // 组织
    2: 'success',   // 志愿者
    0: 'info'       // 普通用户
  }
  return types[role] || 'info'
}

// 获取角色名称
const getRoleName = (role) => {
  const names = {
    1: '管理员',
    3: '组织',
    2: '志愿者',
    0: '普通用户'
  }
  return names[role] || '未知'
}

// 数据是否初始化完成标志
const dataInitialized = ref(false)

// 加载用户列表
const loadUserList = async () => {
  tableLoading.value = true
  dataInitialized.value = false // 加载前重置标志
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      ...searchForm
    }
    
    const res = await getUserList(params)
    if (res && res.code === 200) {
      userList.value = res.data.list || []
      total.value = res.data.total || 0
      
      // 数据加载成功后设置初始化标志
      setTimeout(() => {
        dataInitialized.value = true
      }, 100)
    } else {
      ElMessage.error(res?.message || '获取用户列表失败')
    }
  } catch (error) {
    console.error('获取用户列表出错:', error)
    ElMessage.error('获取用户列表失败，请重试')
  } finally {
    tableLoading.value = false
  }
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  loadUserList()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  currentPage.value = 1
  loadUserList()
}

// 处理新增
const handleAdd = () => {
  dialogType.value = 'add'
  dialogVisible.value = true
  
  // 重置表单
  userFormRef.value?.resetFields()
  Object.keys(userForm).forEach(key => {
    userForm[key] = key === 'status' ? '1' : ''
  })
}

// 处理编辑
const handleEdit = (row) => {
  dialogType.value = 'edit'
  dialogVisible.value = true
  
  // 重置表单
  userFormRef.value?.resetFields()
  
  // 填充表单
  Object.keys(userForm).forEach(key => {
    if (key !== 'password') {
      userForm[key] = row[key]
    } else {
      userForm[key] = ''
    }
  })
}

// 处理删除
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确认删除该用户吗？此操作不可恢复！',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const res = await deleteUser(row.id)
      if (res && res.code === 200) {
        ElMessage.success('删除成功')
        loadUserList()
      } else {
        ElMessage.error(res?.message || '删除失败')
      }
    } catch (error) {
      console.error('删除用户出错:', error)
      ElMessage.error('删除失败，请重试')
    }
  }).catch(() => {
    // 取消删除，不做任何操作
  })
}

// 处理状态变更
const handleStatusChange = async (row, val) => {
  // 如果数据还未初始化完成，不进行状态变更请求
  if (!dataInitialized.value) return
  
  try {
    const res = await changeUserStatus(row.id, val)
    if (res && res.code === 200) {
      const status = val === '1' ? '启用' : '禁用'
      ElMessage.success(`已${status}该用户`)
    } else {
      // 如果失败，恢复原来的状态
      row.status = val === '1' ? '2' : '1'
      ElMessage.error(res?.message || '修改状态失败')
    }
  } catch (error) {
    // 如果发生错误，恢复原来的状态
    row.status = val === '1' ? '2' : '1'
    console.error('修改用户状态出错:', error)
    ElMessage.error('修改状态失败，请重试')
  }
}

// 处理重置密码
const handleResetPwd = (row) => {
  ElMessageBox.confirm(
    '确认重置该用户的密码吗？重置后密码将变为默认密码！',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const res = await resetUserPassword(row.id)
      if (res && res.code === 200) {
        ElMessage.success('密码重置成功')
      } else {
        ElMessage.error(res?.message || '密码重置失败')
      }
    } catch (error) {
      console.error('重置密码出错:', error)
      ElMessage.error('密码重置失败，请重试')
    }
  }).catch(() => {
    // 取消重置，不做任何操作
  })
}

// 处理表单提交
const handleSubmit = async () => {
  if (!userFormRef.value) return
  
  await userFormRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        let res
        
        if (dialogType.value === 'add') {
          // 新增用户
          res = await addUser(userForm)
        } else {
          // 编辑用户
          const { id, password, ...userData } = userForm
          res = await updateUser(id, userData)
        }
        
        if (res && res.code === 200) {
          ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功')
          dialogVisible.value = false
          loadUserList()
        } else {
          ElMessage.error(res?.message || (dialogType.value === 'add' ? '添加失败' : '更新失败'))
        }
      } catch (error) {
        console.error(dialogType.value === 'add' ? '添加用户出错:' : '更新用户出错:', error)
        ElMessage.error(dialogType.value === 'add' ? '添加失败，请重试' : '更新失败，请重试')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 处理分页
const handleSizeChange = (val) => {
  pageSize.value = val
  loadUserList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadUserList()
}

// 页面加载时获取用户列表
onMounted(() => {
  loadUserList()
})
</script>

<style scoped lang="scss">
.account-management {
  .search-card {
    margin-bottom: 20px;
  }

  .table-card {
    .pagination {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
}
</style> 